#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname -- "$0")/log.sh"


# 当前分支的名称
CURRENT_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)

# 受保护的分支
PROTECTED_BRANCH_NAME="master"

# 禁止合并的分支
FORBIDDEN_BRANCH_NAMES=("test" "pre")

# 校验是否能合并
function validCanMerge() {
  MERGE_HEAD=`cat .git/MERGE_HEAD`
  # 合并进来的分支名称
  MERGE_BRANCH_NAME=$(git name-rev $MERGE_HEAD)
   if [[ "$MERGE_BRANCH_NAME" == *"$1"*  ]]; then
        error "检测到非法合并: ${MERGE_BRANCH_NAME//$MERGE_HEAD / } ==into==> $CURRENT_BRANCH_NAME"
        info "撤销合并中..."
        $(git reset --keep HEAD~1)
        info "已撤销合并 done"
        exit 1
    fi
}

# 禁止合并
function forbidMerge(){
  for branchName in $FORBIDDEN_BRANCH_NAMES  
    do
      validCanMerge $branchName    
  done
}

if [[ -e .git/MERGE_HEAD ]]; then
    if [[ ! "${FORBIDDEN_BRANCH_NAMES[@]}"  =~ "$CURRENT_BRANCH_NAME" ]]; then
          forbidMerge
    fi
fi